﻿using System;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections.Generic;

using WoChu.RfClient.Entity;
using WoChu.RfClient.Common;
using WoChu.CF.BaseFrame.Util;

namespace WoChu.RfClient.Duty
{
    public partial class FrmLocationAdjustment : Form
    {
        public FrmLocationAdjustment()
        {
            InitializeComponent();
        }

        private static int iSort = 0;
        //当前货位编码
        private static string sLocationCode = string.Empty;  
        //商品与货位商品数据字典
        private static Dictionary<string, LocationGoodsInfo> _dictLocationGoods = null;
        public static Dictionary<string, LocationGoodsInfo> dictLocationGoods
        {
            get
            {
                if (_dictLocationGoods == null) _dictLocationGoods = new Dictionary<string, LocationGoodsInfo>();
                return _dictLocationGoods;
            }
        }
        //货位编码字典
        private static Dictionary<string, int> _dictLocationCode = null;
        public static Dictionary<string, int> dictLocationCode
        {
            get
            {
                if (_dictLocationCode == null) _dictLocationCode = new Dictionary<string, int>();
                return _dictLocationCode;
            }
        }

        //商品批次库存字典
        private static Dictionary<string, decimal> _dictLocationGoodsBatch = null;
        public static Dictionary<string, decimal> dictLocationGoodsBatch
        {  
            get
            {
                if (_dictLocationGoodsBatch == null) _dictLocationGoodsBatch = new Dictionary<string, decimal>();
                return _dictLocationGoodsBatch;
            }
        }

        //货位和货位库存字典
        private static Dictionary<string, List<LocationInventoryInfo>> _dictLocationInventory = null;
        public static Dictionary<string, List<LocationInventoryInfo>> dictLocationInventory
        {
            get
            {
                if (_dictLocationInventory == null) _dictLocationInventory = new Dictionary<string, List<LocationInventoryInfo>>();
                return _dictLocationInventory;
            }
        }

        private static List<LocationInventoryInfo> lstAdjustment = null;
        private static List<LocationInventoryInfo> _lstListStock = null;
        public static List<LocationInventoryInfo> lstListStock
        {
            get
            {
                if (_lstListStock == null) _lstListStock = new List<LocationInventoryInfo>();
                return _lstListStock;
            }
        }

        private void FrmLocationAdjustment_Load(object sender, EventArgs e)
        {

            List<LocationGoodsInfo> _lstLocationGoods = Duty.LocationAdjustmentUIRule.NewInstance.GetLocationGoodsInfo(LoginBean.Instance.USERCODE).DATA;
 
            if (_lstLocationGoods != null && _lstLocationGoods.Count > 0)
            {
                foreach (var _LocationGoods in _lstLocationGoods)
                {
                    if (!dictLocationGoods.ContainsKey(_LocationGoods.GOODSCODE))
                    {
                        dictLocationGoods.Add(_LocationGoods.GOODSCODE, _LocationGoods);
                    }

                    if (!dictLocationCode.ContainsKey(_LocationGoods.LOCATIONCODE))
                    {
                        dictLocationCode.Add(_LocationGoods.LOCATIONCODE, _LocationGoods.LOCATIONID);
                    }
                }
            }

            List<LocationGoodsBatchInfo> _lstLocationGoodsBatch = Duty.LocationAdjustmentUIRule.NewInstance.GetLocationGoodsBatchInfo(LoginBean.Instance.USERCODE).DATA;
            if (_lstLocationGoodsBatch != null && _lstLocationGoodsBatch.Count > 0)
            {
                foreach (var _LocationGoodsBatch in _lstLocationGoodsBatch)
                {
                    string _key = _LocationGoodsBatch.LOCATIONCODE + "-" + _LocationGoodsBatch.GOODSBATCHCODE;

                    if (!dictLocationGoodsBatch.ContainsKey(_key))
                    {
                        dictLocationGoodsBatch.Add(_key, _LocationGoodsBatch.QTY);
                    }
                }
            }

            txtLocation.Focus();
        }

        //显示扫描行
        private void SelectionBright(string barcode)
        {
            //if (lstLocationGoods == null || lstLocationGoods.Count <= 0) return;
            ////设置已扫描的为加亮
            //List<LocationGoodsInfo> _LocationGoods = lstLocationGoods.FindAll(o => o.Selected);
            //foreach (var _item in _LocationGoods)
            //{
            //    this.dbGridOnShelves.Select(lstLocationGoods.IndexOf(_item));

            //    this.dbGridOnShelves.SelectionBackColor = Color.Green;
            //}

           
            if (string.IsNullOrEmpty(barcode)) return;
            int curIndex = lstAdjustment.FindIndex(x => x.GOODSBATCHCODE == barcode);
            dbGridAdjustment.Select(curIndex);
            this.dbGridAdjustment.SelectionForeColor = Color.Green; 

            //else if (barNo.Length == 6)
            //{
            //    List<LocationGoodsInfo> lstCellNos=lstLocationGoods.FindAll(o=>o.GOODSBATCHCODE==barNo);
            //    foreach(var item in lstCellNos)
            //    {
            //        this.dbGridOnShelves.Select(lstLocationGoods.IndexOf(item)); 
            //        this.dbGridOnShelves.SelectionBackColor = Color.Green; 
            //    }
            //}
            
        }
        
        //扫描排序
        private void Sort(LocationInventoryInfo curitem)
        {

            curitem.Sort = -1;

            lstAdjustment.Sort((x, y) =>
            {
                return x.Sort.CompareTo(y.Sort);
            });
            this.dbGridAdjustment.Refresh();
            curitem.Sort = iSort++;
        }

        private void txtLocation_GotFocus(object sender, EventArgs e)
        {
            txtLocation.Text = string.Empty;
            txtLocation.Focus();
            txtLocation.SelectAll();
        }

        private void txtLocation_LostFocus(object sender, EventArgs e)
        {
            sLocationCode = txtLocation.Text.Trim();
            if (!string.IsNullOrEmpty(sLocationCode))
            {
                txtLocation_KeyDown(sender, new KeyEventArgs(Keys.Enter));
            }
        }

        //回车货位操作
        private void txtLocation_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            try
            {
                sLocationCode = txtLocation.Text.Trim();
                if (sLocationCode != "999")
                {
                    if (string.IsNullOrEmpty(sLocationCode) || !dictLocationCode.ContainsKey(sLocationCode))
                    {
                        MessageBox.Show("请扫正确货位码！");
                        sLocationCode = string.Empty;
                        txtLocation.SelectAll();
                        return;
                    }
                }

                //获取当前货期的商品数据
                if (dictLocationInventory.ContainsKey(sLocationCode))
                {
                    //获取当前货期的商品数据
                    lstAdjustment = dictLocationInventory[sLocationCode];

                    this.adjustmentSource.DataSource = null;
                    this.adjustmentSource.DataSource = lstAdjustment;
                    this.dbGridAdjustment.DataSource = this.dbGridAdjustment;
                    this.dbGridAdjustment.Refresh();
                }

                txtQty.Text = string.Empty;
                txtBarCode.Text = string.Empty;
                txtBarCode.Focus();
                txtBarCode.SelectAll();
            }
            catch (Exception ex)
            {
                txtLocation.SelectAll();
                sLocationCode = string.Empty;
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
        }

        //商品批次条码回车操作
        private void txtBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            if (string.IsNullOrEmpty(sLocationCode))
            {
                sLocationCode = string.Empty;
                txtLocation.SelectAll();
                return;
            }

            try
            {
                string _barCode = txtBarCode.Text.Trim();
                if (string.IsNullOrEmpty(_barCode))
                {
                    MessageBox.Show("请扫描条码！");
                    txtBarCode.Focus();
                    txtBarCode.SelectAll();
                    return;
                }

                //根据扫描的商品批次转换成商品编码
                string _Code = _barCode;
                if (_barCode.Length == 18 && (_barCode.Substring(0, 1) == "0" || _barCode.Substring(0, 1) == "3")) //处理商品
                {
                    _Code = _barCode.Substring(0, 10);

                    if (!dictLocationGoods.ContainsKey(_Code))
                    {
                        _Code = string.Empty;
                    }
                }
                else if (_barCode.Substring(0, 3) == "WOC" && (_barCode.Length == 17 || _barCode.Length == 20))
                {
                    _Code = _barCode.Substring(0, _barCode.Length - 8); 
                    if (!dictLocationGoods.ContainsKey(_Code))
                    {
                        _Code = string.Empty;
                    }
                }
                else
                {
                    _Code = _barCode;
                    if (!dictLocationGoods.ContainsKey(_Code))
                    {
                        _Code = string.Empty;
                    }
                }

                if (string.IsNullOrEmpty(_Code))
                {
                    MessageBox.Show("扫描条码错误！");
                    txtBarCode.Focus();
                    txtBarCode.SelectAll();
                    return;
                }

                Cursor.Current = Cursors.WaitCursor;

                if (lstAdjustment == null)
                {
                    lstAdjustment = new List<LocationInventoryInfo>();
                }
                LocationInventoryInfo curitem = null;
                if (sLocationCode == "999")
                {
                    curitem = lstAdjustment.Find(x => x.GOODSBATCHCODE == _Code);
                }
                else
                {
                    curitem = lstAdjustment.Find(x => x.GOODSBATCHCODE == _barCode);
                }

                if (curitem == null)
                {
                    LocationInventoryInfo _item = new LocationInventoryInfo();
                    LocationGoodsInfo _locationGoods = dictLocationGoods[_Code];

                    string _key = string.Empty;
                    switch (sLocationCode)
                    {
                        case "999":
                            _key = sLocationCode + "-" + _Code;
                            _item.LOCATIONID = 999;
                            _item.LOCATIONCODE = "999";
                            _item.GOODSBATCHCODE = _Code;
                            _item.PRODUCTIONDATE = "";
                            _item.EXPIRYDAYS = 0; 
                            break;
                        default:
                            _key = sLocationCode + "-" + _barCode;
                            _item.LOCATIONID = _locationGoods.LOCATIONID;
                            _item.LOCATIONCODE = _locationGoods.LOCATIONCODE;
                            _item.GOODSBATCHCODE = _barCode;
                            _item.PRODUCTIONDATE = _barCode.Substring(_barCode.Length - 8, 5);
                            _item.EXPIRYDAYS = Convert.ToInt32(_barCode.Substring(_barCode.Length - 3, 3));
                            break;
                    }

                    decimal _Qty = 0;
                    try
                    {
                        _Qty = dictLocationGoodsBatch[_key];
                    }
                    catch
                    {
                        _Qty = 0;
                    }

                    
                    _item.GOODSCODE = _locationGoods.GOODSCODE;
                    _item.GOODSNAME = _locationGoods.GOODSNAME;
                    _item.UNITNAME = _locationGoods.UNITNAME;

                    _item.LOCATIONINVENTORYID = 0; 
                    _item.GOODSID = _locationGoods.GOODSID;
                    _item.WAREHOUSEID = _locationGoods.WAREHOUSEID;
                    _item.CELLNO = _locationGoods.CELLNO;
                    _item.STORAGEDATE = DateTime.Now.ToString("yMMdd");
                    _item.QTY = _Qty; 
                    _item.CREATER = "";

                    curitem = _item;
                    lstAdjustment.Add(curitem);
                    lstListStock.Add(curitem);
                }

                this.adjustmentSource.DataSource = null;
                this.adjustmentSource.DataSource = lstAdjustment;
                this.dbGridAdjustment.DataSource = this.adjustmentSource;
                this.dbGridAdjustment.Refresh();
                Sort(curitem);
                SelectionBright(curitem.GOODSBATCHCODE);
         
                txtQty.Text = string.Empty;
                txtQty.Focus();

            }
            catch (Exception ex)
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {  
                Cursor.Current = Cursors.Default;
            }
        }
        
        //回车数量操作
        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            if (lstAdjustment == null)
            {
                this.txtQty.Text = string.Empty;
                this.txtBarCode.Text = string.Empty;
                this.txtBarCode.Focus();
                this.txtBarCode.SelectAll();
            }

            string _txtQty = this.txtQty.Text.Trim();

            if (!string.IsNullOrEmpty(_txtQty))
            {
                decimal _Qty = 0;
                try
                {
                    _Qty = Convert.ToDecimal(_txtQty);
                }
                catch
                {
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不正确!");
                    this.txtQty.Text = string.Empty;
                    this.txtQty.Focus();
                    return;
                }

                int curIndex = dbGridAdjustment.CurrentRowIndex;
                if (curIndex < 0)
                {
                    MessageBox.Show("请选选择的数据行！");
                    return;
                }

                LocationInventoryInfo curItem = lstAdjustment[curIndex];
                curItem.QTY = _Qty; 

                if (!lstListStock.Contains(curItem))     
                {
                    lstListStock.Add(curItem);
                }

                this.adjustmentSource.DataSource = null;
                this.adjustmentSource.DataSource = lstAdjustment;
                this.dbGridAdjustment.DataSource = this.adjustmentSource;
                this.dbGridAdjustment.Refresh();

                //设置已扫描的为加亮
                SelectionBright(curItem.GOODSBATCHCODE);

                this.lblQtySum.Text = lstAdjustment.Sum(o => o.QTY).ToString();
                this.txtQty.Text = string.Empty;
                this.txtBarCode.Text = string.Empty;
                this.txtBarCode.Focus();
                this.txtBarCode.SelectAll();
            }
        }

        private void dbGridAdjustment_DoubleClick(object sender, EventArgs e)
        {
            int curIndex = dbGridAdjustment.CurrentRowIndex;
            if (curIndex < 0) return;

            LocationInventoryInfo curItem = lstAdjustment[curIndex];
            txtLocation.Text = curItem.LOCATIONCODE;
            txtBarCode.Text = curItem.GOODSBATCHCODE;
            SelectionBright(curItem.GOODSBATCHCODE);
            txtQty.Text = string.Empty;
            txtQty.Focus();
            txtQty.SelectAll();
        }
        
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (lstListStock != null && lstListStock.Count > 0)
                {
                    if (WoChu.CF.BaseFrame.Util.MessageBoxEx.Question("是否提交？") == DialogResult.No) return;

                    var re = Duty.LocationAdjustmentUIRule.NewInstance.Submit(LoginBean.Instance.USERCODE, lstListStock);

                    if (re.RESULT=="1")
                    {
                        lstAdjustment.Clear();
                        lstListStock.Clear();
                        dictLocationInventory.Clear();
                        this.adjustmentSource.DataSource = null;
                        this.dbGridAdjustment.DataSource = this.adjustmentSource;
                        this.dbGridAdjustment.Refresh();

                        this.listStockSource.DataSource = null;
                        this.dbGridListStock.DataSource = this.listStockSource;
                        this.dbGridListStock.Refresh();

                        txtLocation.Text = string.Empty;
                        txtBarCode.Text = string.Empty;
                        txtQty.Text = string.Empty;
                        lblQtySum.Text = string.Empty;
                        lblCount.Text = string.Empty;
                        lblSum.Text = string.Empty;
                        tabControlTakeStock.SelectedIndex = 0;
                        txtLocation.Focus();
                        txtLocation.SelectAll();
                        MessageBox.Show("提交成功！");
                    }
                    else
                    {
                        MessageBox.Show(re.MESSAGE);
                        return;
                    }
                }
                else
                {
                    MessageBoxEx.Show("请扫描盘点数据再提交！");
                    return;
                }
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
 
        private void tabControlTakeStock_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlTakeStock.TabPages[tabControlTakeStock.SelectedIndex].Name == tabListStock.Name)
            {
                if (lstListStock == null || lstListStock.Count <= 0) return;

                this.listStockSource.DataSource = null;
                this.listStockSource.DataSource = lstListStock;
                this.dbGridListStock.DataSource = this.listStockSource;
                this.dbGridListStock.Refresh();

                this.lblCount.Text = (from itme in lstListStock group itme by itme.LOCATIONCODE into g select new { LOCATIONCODE = g.Count() }).Count().ToString();
                this.lblSum.Text = lstListStock.Sum(o => o.QTY).ToString();
            }
        }

        private void dbGridListStock_DoubleClick(object sender, EventArgs e)
        {
            int curIndex = dbGridListStock.CurrentRowIndex;
            if (curIndex < 0) return;
            try
            {

                LocationInventoryInfo curItem = lstListStock[curIndex];

                string ltCode = curItem.LOCATIONCODE;
                string gbName = curItem.GOODSNAME;

                string Message = string.Format("货位:{0}, 名称:{1}, \n 是否删除该数据？", ltCode, gbName);
                if (MessageBoxEx.Question(Message) == DialogResult.Yes)
                {
                    lstListStock.Remove(curItem);
                    this.listStockSource.DataSource = null;
                    this.listStockSource.DataSource = lstListStock;
                    this.dbGridListStock.DataSource = this.listStockSource;
                    this.dbGridListStock.Refresh();
                }
            }
            catch (Exception ex)
            {
                TraceEx.Write(ex.Message);
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("删除数据失败!");
            }
            finally
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
            }

        }

        private void FrmLocationAdjustment_Closed(object sender, EventArgs e)
        {
            if (lstListStock != null && lstListStock.Count > 0)
            {
                lstListStock.Clear();
                lstListStock.Clear();
                dictLocationGoods.Clear();
                dictLocationGoodsBatch.Clear();
            }
            this.Close();
            this.Dispose();
        }

        private void FrmLocationAdjustment_Closing(object sender, CancelEventArgs e)
        {
            if (MessageBoxEx.Question("将退出该窗体清空数据，确认是否退出？") == DialogResult.No)
                e.Cancel = true;
        }

   
    }
}